package core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * Klasa do logowania błedów
 * @author Marcin
 */
public class ErrorLogger {
    private ErrorLogger(){}
    
    private static class SqlConnectionHolder {
        private static final ErrorLogger INSTANCE = new ErrorLogger();
    }

    public static ErrorLogger getInstance() {
        return SqlConnectionHolder.INSTANCE;
    }
    /**
     * Zapisuje błąd i ewentualnie wyświetla użytkownikowi informacje
     * @param disc Opis błędu
     * @param show Jeśli true wyświetla informacje 
     * @param frame Uchwyt okna , mozna dać null
     */
    public void log(String disc,boolean show,JFrame frame)
    {
        File dir = new File(defaultDirectory() + "\\Przychodnia");
        if(!dir.exists()) {
            dir.mkdir();
        }
        File dirLog = new File(dir.getPath() + "\\log");
        if(!dirLog.exists()) {
            dirLog.mkdir();
        }
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
        File f = new File(dirLog.getPath() + "\\" + df.format(date).replace("/", "") + ".log");
        if(!f.exists()){
            try {
                f.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(ErrorLogger.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        FileWriter fstream;
        BufferedWriter out;
        try {
            fstream = new FileWriter(f,true);
            out = new BufferedWriter(fstream);
            out.append(df2.format(date) + ":" + disc);
            out.newLine();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(ErrorLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(show)
        {
            JOptionPane.showMessageDialog(frame,
                disc,
                "Przychodnia @ UJ",
                JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private String defaultDirectory()
    {
        String OS = System.getProperty("os.name").toUpperCase();
        if (OS.contains("WIN"))
            return System.getenv("APPDATA");
        else if (OS.contains("NUX"))
            return System.getProperty("users.home");
        return System.getProperty("users.dir");
    }

}
